import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { Form, Input, InputNumber, Switch, Slider, Card, Space, Row, Col, Typography, Select, Divider } from 'antd';
import { selectSelectedSegment, SelectedSegmentInfo } from '@/store/selectedSegmentSlice';
import '@/styles/BaseConfigForm.css';
import { updateSegment } from '@/services/project';
import { createDebounce } from '@/utils/debounceUtils';
import eventBus from '@/utils/eventBus';
import styled from 'styled-components';

const { Text } = Typography;

// 全局深色主题样式
const GlobalDarkThemeStyle = styled.div`
  .ant-form-item-label > label {
    color: #ffffff !important;
  }
  .ant-slider-rail {
    background-color: #555555 !important;
  }
  .ant-slider-track {
    background-color: #715BB8 !important;
  }
  .ant-slider-handle {
    border-color: #ffffff !important;
    background-color: #3C3C3C !important;
  }
  .ant-slider-handle:hover {
    border-color: #715BB8 !important;
  }
  .ant-slider-handle:focus {
    box-shadow: 0 0 0 5px rgba(113, 91, 184, 0.3) !important;
  }
`;

// 辅助组件：用于创建标签-滑块-数值输入的组合行
const SliderInputRow: React.FC<{
  label: string;
  name: string | string[];
  sliderProps: any;
  inputProps: any;
}> = ({ label, name, sliderProps, inputProps }) => (
  <Form.Item>
    <Row align="middle" gutter={16}>
      <Col span={6}>
        <Text style={{ color: '#FFFFFF' }}>{label}</Text>
      </Col>
      <Col span={12}>
        <Form.Item name={name} noStyle>
          <Slider {...sliderProps} />
        </Form.Item>
      </Col>
      <Col span={6}>
        <Form.Item name={name} noStyle>
          <InputNumber
            style={{
              width: '90%',
              background: 'linear-gradient(135deg,rgb(90, 83, 83) 0%, #1e1e1e 100%)',
              color: '#ffffff',
              border: '1px solid #404040'
            }}
            {...inputProps}
          />
        </Form.Item>
      </Col>
    </Row>
  </Form.Item>
);

// 表单数据接口，基于SelectedSegmentInfo
interface AudioConfigFormData extends SelectedSegmentInfo {
  // 继承SelectedSegmentInfo的所有字段
}
const AudioConfigForm: React.FC = () => {
  const [form] = Form.useForm();

  // 从Redux store获取选中的片段信息
  const selectedSegment = useSelector(selectSelectedSegment);

  const updateSegmentInDatabase = async (allValues: AudioConfigFormData) => {
    try {
      const updateData = {
        type: 'audio',
        start: allValues.start,
        duration: allValues.duration,
        material_id: allValues.material_id,
        segment_config: {
          volume: allValues.volume
        }
      };

      // 调用更新接口
      await updateSegment(allValues.draftId, allValues.trackId, allValues.id, updateData);
      // 发送事件总线通知，获取最新草稿数据
      eventBus.emit('draft:updated', { draftId: allValues.draftId });

    } catch (error) {
      console.error('更新片段失败:', error);
    }
  };

  const debouncedUpdateSegment = createDebounce(updateSegmentInDatabase, {
    delay: 800,
    cancelThreshold: 1000
  });
  // 处理值变化
  const handleValuesChange = (changedValues: any, allValues: AudioConfigFormData) => {
    const changedValuesWithMaterialId = {
      draftId: selectedSegment.draftId,
      trackId: selectedSegment.trackId,
      id: selectedSegment.id,
      material_id: selectedSegment.material_id,
      start: allValues.start,
      duration: allValues.duration,
      volume: allValues.volume
    }
    debouncedUpdateSegment.execute(changedValuesWithMaterialId);
  };

  // 初始化表单值
  useEffect(() => {
    if (selectedSegment && selectedSegment.type === 'audio') {
      form.setFieldsValue(selectedSegment);
    } else {
      // 如果没有选中音频片段，重置表单
      form.resetFields();
    }
  }, [selectedSegment, form]);

  return (
    <GlobalDarkThemeStyle>
      <Form
        form={form}
        layout="vertical"
        onValuesChange={handleValuesChange}
      >
        {/* 时间配置 */}
        <Card title={<div style={{ color: '#FFFFFF' }}>时间配置</div>} size="small" style={{ marginBottom: 16 }} className={'form-card'}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="目标开始时间"
                name={['start']}
                rules={[{ required: true, message: '请输入开始时间' }]}
              >
                <InputNumber
                  min={0}
                  placeholder="开始时间（微秒）"
                  style={{
                    width: '100%',
                    backgroundColor: '#2a2a2a',
                    borderColor: '#434343',
                    color: '#ffffff'
                  }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="目标持续时间"
                name={['duration']}
                rules={[{ required: true, message: '请输入持续时间' }]}
              >
                <InputNumber
                  min={1}
                  placeholder="持续时间（微秒）"
                  style={{
                    width: '100%',
                    backgroundColor: '#2a2a2a',
                    borderColor: '#434343',
                    color: '#ffffff'
                  }}
                />
              </Form.Item>
            </Col>
          </Row>
        </Card>

        {/* 播放设置 */}
        <Card title={<div style={{ color: '#FFFFFF' }}>播放设置</div>} size="small" style={{ marginBottom: 16 }} className={'form-card'}>
          <SliderInputRow
            label="音量"
            name="volume"
            sliderProps={{ min: 0, max: 2, step: 0.01 }}
            inputProps={{ min: 0, max: 2, step: 0.01 }}
          />
        </Card>
      </Form>
    </GlobalDarkThemeStyle>
  );
};

export default AudioConfigForm;
export type { AudioConfigFormData };